package com.heima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Result;
import com.heima.domain.dto.VmTypeDto;
import com.heima.domain.po.VmType;
import com.heima.domain.vo.VmTypeVo;
import com.heima.mapper.VmTypeMapper;
import com.heima.service.VmTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class VmTypeServiceImpl extends ServiceImpl<VmTypeMapper, VmType> implements VmTypeService {
    /**
     * 设备分页查询
     *
     * @param pageIndex
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Result getByPage(Integer pageIndex, Integer pageSize, String name) {
        Page<VmType> page = new Page<>(pageIndex,pageSize);
        Page<VmType> page1 = this.lambdaQuery().like(StringUtils.hasText(name), VmType::getName, name).page(page);
        List<VmTypeVo> ts = BeanUtil.copyToList(page1.getRecords(), VmTypeVo.class);
        Result of = Result.of(page1);
        of.setCurrentPageRecords(ts);
        return of;
    }

    /**
     * 添加设备
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean addVmType(VmTypeDto dto) {
        VmType vmType = new VmType();
        BeanUtils.copyProperties(dto,vmType);
        try {
            this.save(vmType);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 修改设备
     *
     * @param typeId
     * @param dto
     * @return
     */
    @Override
    public Boolean updateVmType(Integer typeId, VmTypeDto dto) {
        VmType vmType = new VmType();
        BeanUtils.copyProperties(dto,vmType);
        try {
            lambdaUpdate().eq(typeId != null,VmType::getTypeId,typeId).update(vmType);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
